/**
 * 
 */
package com.aodesoft.demo.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.aodesoft.base.BaseDao;
import com.aodesoft.pojo.Demo;

/**
 * 
 * @author tang
 * @date 2011-12-3
 */
@Repository
public class DemoDao extends BaseDao<Demo, Integer>{
	
	/**
	 * 假如BaseDao不能满足所需的功能，可以另外写，但是注意不要重名
	 * @author tang
	 * @date 2011-12-4
	 * @return 
	 */
	public List<Demo> queryDesc(){
		//使用HibernateTemplate
		//HibernateTemplate ht=new HibernateTemplate(this.getSessionFactory());
		List<Demo> lst=null;
		Transaction tx = null;
		Session session = null;
		String sql="from Demo demo order by demo.id desc";
		try {
			session=this.getSessionFactory().openSession(); 
			tx=session.beginTransaction();
			Query q=session.createQuery(sql);
			lst=q.list();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		}finally{
			session.close();
		}
		return lst;
	}
	/**
	 * 使用hibernatetempla
	 * @author tang
	 * @date 2011-12-4
	 * @param demo
	 */
	public void insertTest(Demo demo){
		HibernateTemplate ht=new HibernateTemplate(this.getSessionFactory());
		ht.save(demo);
		
	}
	/**
	 * 查询部分字段
	 * @author tang
	 * @date 2011-12-4
	 */
	public void getPojo(){
		//使用HibernateTemplate
		//HibernateTemplate ht=new HibernateTemplate(this.getSessionFactory());
		List<Demo> lst=null;
		Transaction tx = null;
		Session session = null;
		String sql="select id,title from Demo d order by id desc";
		try {
			session=this.getSessionFactory().getCurrentSession(); 
			tx=session.beginTransaction();
			SQLQuery q=session.createSQLQuery(sql);
			q.setResultTransformer(Transformers.aliasToBean(Demo.class));
			q.addScalar("id",Hibernate.INTEGER);
			q.addScalar("title",Hibernate.STRING);
			lst=q.list();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void delTest(){
		
		HibernateTemplate ht=new HibernateTemplate(this.getSessionFactory());
		Demo d=new Demo();
		d.setId(3);
		ht.delete( d );
	}
}
